import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class demo1 {
    public static void main(String[] args) throws SQLException {
        Scanner s = new Scanner(System.in);
        System.out.println("请输入你的学号：");
        int id = s.nextInt();
        System.out.println("请输入你的姓名：");
        String name = s.next();
        //1.找到数据库服务器
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test2?characterEncoding:utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1234");

        //2.建立与数据库的连接,此步完成过后才能进行与mysql的请求-响应 交互
        Connection connection = dataSource.getConnection();

        //3.构造sql
        //String sql = "insert into student values(1,\"张三\")";
        //String sql = "insert into student values(1,'张三')";
        String sql = "insert into student values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);

        //4.将sql发送给数据库服务器
        int n = statement.executeUpdate(); // 返回值表示受到影响的列数
        System.out.println("n = " + n);
        //5.关闭连接，释放资源。注意释放顺序：后获取的资源，先释放

        statement.close();
        connection.close();
    }
}
